'use strict';
const http = require("http"), url = require("url"), fs = require('fs'), path = require("path");

module.exports = (request, response)=>{
    //读取本地文件
    let path = request.SITE["root"] + request.GET.pathname;
    fs.stat(path, onStat);
	
	function onStat(err, stats){
		if(err && err.code == 'ENOENT'){
			let options = request.SITE.proxy;
			if(!options){
				response.statusCode = 404;
				response.end("not find file");
				return;
			}
			options.path = request.url;
			options.method = request.method;

			if(options.port == 443)
				https.request(options, hld).end();
			else
				http.request(options, hld).end();

			function hld(res){
				response.statusCode = res.statusCode;
				if(response.statusCode == 302) response.setHeader("location", res.headers["location"]);
				res.pipe(response);
				console.log("write file ", request.GET.pathname);
				let cd = Buffer.allocUnsafe(0);
				res.on("data", (chunk)=>{
					cd = Buffer.concat([cd, chunk], cd.length + chunk.length);
				});
				res.on("end", ()=>{
					if(res.statusCode == 200){
						const cdir = require("./cdir");
						cdir(request.SITE["root"], request.GET.pathname, ()=>{
							if(request.GET.pathname.substr(-1, 1) == '/') request.GET.pathname += "index.html"; 
							fs.writeFile(request.SITE["root"] + request.GET.pathname, cd, function(err){
								if(err){
									console.log("write file error", request.url, err);
									return;
								}
								console.log("write end", request.url);
							});
						});
					}
				});
			}
		}else{
			if(stats.isDirectory()){
				path += "/index.html";
				fs.stat(path, onStat);
			}else{
				if(request.headers['if-modified-since'] == stats.mtime.toUTCString()){
					response.statusCode = 304;
					response.end();
				}else{
					response.setHeader("last-modified", stats.mtime.toUTCString());
					let stream = fs.createReadStream(path);
					stream.pipe(response);				
				}
			}
		}
	}
}